import LRU from 'lru-cache';
import axios from "axios";
import { version, company_id, channelId, pagination } from "@/config";
import { formatDate } from "@/utils";

const baseURL = process.env.baseUrl;
const headers = {
  "Accept": "application/json",
  "content-type": "application/json",
  "company_id": company_id,
  "channelId": channelId,
  "X-TOKEN": "",
};

// 设置数据缓存有效时间，线上环境1h
const cache = new LRU({
  max: 500,
  maxAge: process.env.NEXT_PUBLIC_ENV === 'production' ? 1000*60*60 * 1 : 1000*60*5
});

/*
* *****  首页  ******
* 特价促销、今日推荐
* 获取目的地（林芝、拉萨、阿里）相关数据
*/ 

// 促销/推荐
export async function homePage_recommend_SSR() {

  const cache_key = `/ssop/api/goods-v${version}/applet/goods/list/channel/homePage_recommend_SSR`,
        cache_data = cache.get(cache_key);

  if(cache_data){
    return { ssr: cache_data }
  }else{
    let { data: res = {} } = await axios.get(
      baseURL + `/ssop/api/goods-v${version}/applet/goods/list/channel?offset=1&pageSize=4&destinationId=`,
      { headers } 
    )
    let ssr = [];
    if (res.code === 0 && res.data && res.data.records) {
      ssr = res.data.records
    }

    cache.set(cache_key, ssr);

    return { ssr }
  }
}

// ***** 旅游数据渲染 *****
export async function destinationPart_SSR(destination, params = {t: 5, h: 1, r: 4}, set_cache = true) {

  const cache_key = `/ssop/api/goods-v${version}/applet/goods/list/channel/destinationPart_SSR/${destination.id}`,
        cache_data = cache.get(cache_key);
  
  if(set_cache && cache_data){
    return { 
      ssr: { ...cache_data }
    }
  }else{
    const { id: destinationId } = destination,
          { r: r_size, h: h_size, t: t_size } = params;
    const { data: res_route = {} } = await destinationByID_Route(destinationId, r_size);
    const { data: res_hotel = {} } = await destinationByID_Hotel(destinationId, h_size);
    const { data: res_ticket = {} } = await destinationByID_Ticket(destinationId, t_size);

    let ssr_route = [], ssr_hotel = [], ssr_ticket = [];
    if (res_route.code === 0 && res_route.data && res_route.data.records) {
      ssr_route = res_route.data.records
    }
    if (res_hotel.code === 0 && res_hotel.data && res_hotel.data.records) {
      ssr_hotel = res_hotel.data.records
      if(ssr_hotel.length > 1){
        ssr_hotel = ssr_hotel.slice(0,1)
      }
    }
    if (res_ticket.code === 0 && res_ticket.data && res_ticket.data.records) {
      ssr_ticket = res_ticket.data.records
    }
    
    set_cache && cache.set(cache_key, { ssr_route, ssr_hotel, ssr_ticket });

    return { 
      ssr: { ssr_route, ssr_hotel, ssr_ticket }
    }
  }
}

// 根据目的地ID，获取景区/酒店/线路
async function destinationByID_Ticket(id, size) {
  return axios.get(
    baseURL + `/ssop/api/goods-v${version}/applet/goods/list/channel?projectId=1&offset=1&pageSize=${size}&destinationId=${id}`,
    { headers }
  )
}
async function destinationByID_Hotel(id, size) {
  return axios.get(
    baseURL +  `/ssop/api/goods-v${version}/applet/goods/list/channel?projectId=3&offset=1&pageSize=${size}&destinationId=${id}`,
    { headers }
  )
}
async function destinationByID_Route(id, size) {
  return axios.get(
    baseURL + `/ssop/api/goods-v${version}/applet/goods/list/channel?categoryId=2&projectId=2&offset=1&pageSize=${size}&destinationId=${id}`,
    { headers } 
  )
}

// ***** 攻略 *****
export async function guidePart_SSR({ limit = 3, offset = 1, pageSize = 5 }) {

  const cache_key = `/ssop/api/cms-v${version}/applet/strategy/listBycategoryId/channel/guidePart_SSR?categoryId=-1&offset=${offset}&pageSize=${pageSize}`,
        cache_data = cache.get(cache_key);

  if(cache_data){
    return { 
      ssr: { ...cache_data }
    }
  }else{

    const { data: res_scan = {} } = await guideMax_Scan(limit);
    const { data: res_new = {} } = await guideMax_New(offset, pageSize);

    let ssr_scan = [], ssr_new = [];
    if (res_scan.code === 0 && res_scan.data) {
      ssr_scan = res_scan.data
    }
    if (res_new.code === 0 && res_new.data && res_new.data.records) {
      ssr_new = res_new.data.records
    }

    return {
      ssr: {
        ssr_scan,
        ssr_new
      }
    }
  }
}

// 获取浏览器最高攻略、最新攻略
async function guideMax_Scan(limit) {
  return axios.get(
    baseURL + `/ssop/api/cms-v${version}/strategy/list/viewNumber?limit=${limit}`,
    { headers }
  )
}
export async function guideMax_New(offset, pageSize) {
  return axios.get(
    baseURL +  `/ssop/api/cms-v${version}/applet/strategy/listBycategoryId/channel?categoryId=-1&offset=${offset}&pageSize=${pageSize}`,
    { headers }
  )
}


// 热门景区/线路
export async function hotProductList_SSR(type) {
  
  let ssr = [],
    res = {};

  if (type === "/ticket") {
    // 景区
    res = await axios.get(
      baseURL + `/ssop/api/goods-v${version}/applet/goods/list/channel?projectId=1&offset=1&pageSize=5`,
      { headers }
    );
  } else if (type === "/line") {
    // 线路
    res = await axios.get(
      baseURL + `/ssop/api/goods-v${version}/applet/goods/list/channel?categoryId=2&projectId=2&offset=1&pageSize=5`,
      { headers }
    );
  }

  if (res.status === 200 || res.status === 304) {
    const { data } = res;
    if (data.code === 0 && data.data && data.data.records) {
      ssr = data.data.records;
    }
  }

  return { ssr };
}

// 产品/攻略列表
export async function productList_SSR(type, { pathname, query }) {
  let url = baseURL,
    method = "GET",
    data = {};
  let currPage = pathname.includes('_') ? (pathname.split('_')[1] || 2) : 1,
      pageSize = pagination.pageSize,
      offset = (currPage - 1) * pageSize + 1;
  switch (type) {
    case "/hotel": {
      const { date='', keyword='', r } = query;
      const roomTypeList = r ? r.split(',') : [];
      const [start, end] = date.includes('_') ? date.split('_') : [];
      method = "POST";
      url += `/ssop/api/goods-v${version}/applet/goods/es/list/stay`;
      data = {
        offset,
        pageSize,
        startDate: start || formatDate(new Date()),
        endDate: end || formatDate(new Date(), 1),
        keyWords: decodeURIComponent(keyword),
        roomTypeList
      };
      break;
    }
    case "/line": {
      const { city='', r='', s='', g='' } = query;
      method = "POST";
      url += `/ssop/api/goods-v${version}/applet/goods/list/channel`;
      data = {
        categoryId: 2,
        projectId: 2,
        offset,
        pageSize,
        goodsStart: city
      };
      if(r || s || g){
        data["lineTag"] = {
          tagCollect: g,
          tagRecommend: r,
          tagServePoint: s,
        };
      }
      break;
    }
    case "/ticket": {
      const { city='', tag='' } = query;
      url += `/ssop/api/goods-v${version}/applet/goods/list/channel`;
      url += `?projectId=1&offset=${offset}&pageSize=${pageSize}&destinationId=${encodeURIComponent(city)}&tag=${encodeURIComponent(tag)}`;
      break;
    }
    case "/car": {
      url += `/ssop/api/goods-v${version}/applet/goods/list/channel`;
      url += `?projectId=2&categoryId=1&offset=${offset}&pageSize=${pageSize}`;
      break;
    }
    case "/guide": {
      url += `/ssop/api/cms-v${version}/applet/strategy/listBycategoryId/channel`;
      url += `?categoryId=-1&offset=${offset}&pageSize=${pageSize}`;
      break;
    }
  }
  const { data: res = {} } = await axios({
    method,
    url,
    headers,
    data,
  });
  let ssr = [], total = 0;
  if (res.code === 0 && res.data && res.data.records) {
    ssr = res.data.records;
    if (ssr.length) {
      total = ssr[0].total;
    }
  }
  return { ssr, total };
}

// 产品详情
export async function productDetail_SSR(type, id, daterange) {
  let url = baseURL,
    method = "GET",
    data = {};
  switch (type) {
    case "/guide/": {
      url += `/ssop/api/cms-v${version}/applet/strategy/h5/detail/${id}`;
      break;
    }
    case "/hotel/": {
      let [startDate, endDate] = [formatDate(new Date()), formatDate(new Date(), 1)];
      if(daterange && daterange.startDate && daterange.endDate){
        startDate = daterange.startDate;
        endDate = daterange.endDate;
      }
      url += `/ssop/api/goods-v${version}/applet/goods/detail?goodsId=${id}&startDate=${startDate}&endDate=${endDate}`;
      break;
    }
    default: {
      url += `/ssop/api/goods-v${version}/applet/goods/detail?goodsId=${id}`;
      break;
    }
  }
  const { data: res = {} } = await axios({
    method,
    url,
    headers,
    data,
  });
  let ssr = [], _data = {};
  if (res.code === 0 && res.data) {
    _data = res.data;
    ssr = _data.details || _data.contentList || [];
  }
  return {
    ssr,
    ssr_data: _data,
  };
}

// 获取目的地列表
export async function destinationList_SSR() {
  const { data: res = {} } = await axios.get(
    baseURL + `/ssop/api/goods-v${version}/destination/list?pageNo=1&pageSize=20`,
    { headers }
  );
  let ssr = [];
  if (res.code === 0 && res.data && res.data.records) {
    ssr = res.data.records;
  }
  return { ssr };
}

// 获取目的地详情
export async function destinationDetail_SSR(id) {
  const { data: res = {} } = await axios.get(
    baseURL + `/ssop/api/goods-v${version}/destination/detail?id=${id}`,
    { headers }
  );
  let ssr = [],
    city = "";
  if (res.code === 0 && res.data && res.data.detail) {
    ssr = JSON.parse(res.data.detail);
    city = res.data.name;
  }
  return { ssr, city };
}

// 公司简介
export async function companyPage_SSR(id) {
  const { data: res = {} } = await axios.get(
    baseURL + `/ssop/api/cms-v${version}/applet/strategy/h5/detail/${id}`,
    { headers }
  );
  let ssr = [],
      imgs = [];
  if (res.code === 0 && res.data) {
    ssr = res.data.contentList;
    imgs = res.data.pictureList;
  }
  return { ssr, imgs };
}